package com.hksj.wmp.filter;

import com.hksj.jetlinks.filter.AbstractAuthenticationTokenFilter;
import com.hksj.jetlinks.model.LoginUser;
import com.hksj.wmp.constant.WxConstants;
import com.hksj.wmp.manager.WxTokenManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

@Component
public class WxAuthenticationTokenFilter extends AbstractAuthenticationTokenFilter {
 
    @Autowired
    private WxTokenManager wxTokenManager;
 
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String token = request.getHeader(WxConstants.MINI_PROGRAM_TOKEN);
        if (StringUtils.hasText(token)) {
            LoginUser loginUser = wxTokenManager.getUserInfo(token);
            if(!Objects.isNull(loginUser)){
                UsernamePasswordAuthenticationToken authenticationToken =
                        new UsernamePasswordAuthenticationToken(loginUser,null,loginUser.getAuthorities());
                SecurityContextHolder.getContext().setAuthentication(authenticationToken);
            }
        }
        filterChain.doFilter(request, response);
    }
}